package org.jsbd.boss.task;

import java.util.Date;

import javax.annotation.Resource;

import org.jsbd.boss.common.redis.RedisClient;
import org.jsbd.boss.service.IBookService;
import org.jsbd.boss.util.CacheKey;
import org.jsbd.boss.util.DateUtil;
import org.jsbd.boss.util.PropertiesUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class BookRevertTask implements Runnable {

	@Resource
	private IBookService bookService;

	@Autowired
	private RedisClient<String, Object> redisClient;

	// 用于判断定时任务是否开启
	private final static String QUARTZ_FLAG_ON = "on";
	private final static String THREAD_NAME = "bookRevertTread";
	// 定时任务开关：默认为off
	private String quartzFlag = PropertiesUtil.getValue("book_revert_task_flag", "off");
	private static final Logger LOGGER = LoggerFactory.getLogger(BookRevertTask.class);
	// 间隔一分钟
	private static final long SPACE_TIME = 1000 * 60;
	// private AtomicInteger index = new AtomicInteger(0);
	// private volatile int status = 0;

	public void start() {
		Thread t = new Thread(this);
		t.setName(THREAD_NAME);
		t.setDaemon(true);
		t.start();
	}

	@Override
	public void run() {
		// 只有当定时任务为on的时候才会去执行业务逻辑
		if (QUARTZ_FLAG_ON.equalsIgnoreCase(quartzFlag)) {
			while (true) {
				try {

					Object obj = redisClient.get(CacheKey.BOOK_REVERT_TIME);
					if (obj == null) {
						LOGGER.error("书籍管理恢复可下载总数---出错,未设置执行时间！");
						Thread.sleep(SPACE_TIME);
						continue;
					}

					Date revertDate = DateUtil.stringToDate(obj.toString(), DateUtil.DATE_PATTEN_YY_MM_DD_HHMMSS);

					long revertTime = revertDate.getTime();
					long nowTime = System.currentTimeMillis(); // 获取当前时间的毫秒数

					long space = revertTime - nowTime;
					if (space >= 0 && space < SPACE_TIME) {
						int count = bookService.revertAllBookPayMoney();
//						redisClient.remove(CacheKey.BOOK_REVERT_TIME);
						LOGGER.info("书籍管理恢复可下载总数已执行,{}条记录已支付被清零", count);
					}

					Thread.sleep(SPACE_TIME);

				} catch (InterruptedException e) {
					LOGGER.error("书籍管理恢复可下载总数任务出错", e);
				}
			}
		}
	}

	public String getQuartzFlag() {
		return quartzFlag;
	}

	public void setQuartzFlag(String quartzFlag) {
		this.quartzFlag = quartzFlag;
	}

	public static String getQuartzFlagOn() {
		return QUARTZ_FLAG_ON;
	}

}
